package com.gdth.bank.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gdth.coder.encrypt.Encryption;
import com.gdth.core.widget.BaseActivity;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.utils.GsonUtil;
import com.gdth.utils.TimerInstance;

import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.event.CjkhjlListEvent;
import com.gdth.bank.presenter.LoginPresenter;
import com.gdth.bank.utils.SharedPreferencesUtil;
import com.gdth.bank.utils.safeSoftBoard.SafeEdit;
import com.gdth.bank.view.LoginView;
import com.gdth.database.bean.TAppYh;
import com.gdth.bank.utils.AntiHijackingUtil;
import com.gdth.bank.utils.AppUtil;

public class LoginActivity extends BaseActivity implements LoginView{
    @ViewInject(id=R.id.login_btn_login, click="loginClick") Button view_login;
    @ViewInject(id=R.id.login_edit_zh) SafeEdit view_userName;
    @ViewInject(id=R.id.login_edit_mm) SafeEdit view_password;
    @ViewInject(id=R.id.login_checkBox)  CheckBox view_rememberMe;
    @ViewInject(id=R.id.all_background) LinearLayout all_background;
    LoginPresenter mLoginPresenter;
    private static final int MENU_EXIT = Menu.FIRST - 1;
    private static final int MENU_ABOUT = Menu.FIRST;   
    private StringBuffer inputString = new StringBuffer();
    private String inputStr = "";
    String oldStr = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        // 禁止截屏
        getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_login);
        view_userName.clearAll = false;
        view_password.clearAll = true;
        initView();
        init();
    }
    ArrayList<String> images;
	private void init(){
		//view_userName.performClick();
		view_password.addTextChangedListener(new TextWatcher() {
			   
			   @Override
			   public void onTextChanged(CharSequence s, int start, int before, int count) {
			    // TODO Auto-generated method stub
				
			   }
			   
			   @Override
			   public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			    // TODO Auto-generated method stub
			    
			   }
			   
			   @Override
			   public void afterTextChanged(Editable s) {
			    // TODO Auto-generated method stub
				  
				   
			    inputStr = s.toString();
			    if(inputStr.length() == 0){
			    	inputString.setLength(0); 
			    	return;
				}
			    if(inputStr.length() < inputString.length()){
			    	 inputString.setLength(0);  
			    	 
			    	 return ;
			    }
			    if(inputString.length() < inputStr.length() ){
			    	inputString.append(inputStr.substring(inputString.length(), inputStr.length()));
			    }
			    
			    int length = inputStr.length();
			    String showStr = "";
			    if(length == 0) {
			    	view_password.setText("");
			    }else {
			     for(int i = 0 ; i < length ; i ++) {
			      showStr = showStr + "*";
			     }
			    }
			    if(!inputStr.equals(showStr)){
			    	view_password.setText(showStr);
			    }
			   }
			  });
	}
	
//	private void getTbxxbList() {
//		// TODO Auto-generated method stub
//		new DownLoadThread().startDownload();
//	}
    @Override
    protected void setStatusBar() {
//        StatusBarUtil.setColor(this, AppUtil.getColor(this, R.color.black), 1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        menu.add(0, MENU_EXIT, 0, getResources().getText(R.string.MENU_EXIT));
        menu.add(0, MENU_ABOUT, 0, getResources().getText(R.string.MENU_ABOUT));
        
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        super.onMenuItemSelected(featureId, item);
        switch (item.getItemId()) {
            case MENU_EXIT:
                exit();
                break;
            case MENU_ABOUT:
                alertAbout();
                break;
        }
        return true;
    }

    /**
     * 初始化
     * */
    private void initView() {
    	// all_background   - 添加背景照片
//    	String path = ToolUtil.getImagePath(ToolUtil.LoginBackGround)   ;
//    	File imageFile = new File(path);
//    	if(imageFile.exists()) {
//    		Glide.with(this).load(Uri.fromFile(imageFile)).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
//            .into(new ViewTarget<View, GlideDrawable>(all_background) {
//                                           //括号里为需要加载的控件
//                @Override
//                public void onResourceReady(GlideDrawable resource,
//                        GlideAnimation<? super GlideDrawable> glideAnimation) {
//                	this.view.setBackground(resource.getCurrent());
//                }
//
//            });
//    	}
    	
        SharedPreferences share = getSharedPreferences(AppUtil.SHARE_LOGIN_TAG, 0);
        String userName = share.getString(AppUtil.SHARE_LOGIN_USERNAME, "");

        if (!"".equals(userName)) {
            view_userName.setText(userName);
            view_rememberMe.setChecked(true);
        } 
        share = null;

        mLoginPresenter = new LoginPresenter(this);
    }
    
    @Override  
    protected void onStart() {  
    	TimerInstance.getInstance().stop();
        super.onStart();  
    }  
      
    //Activity从后台重新回到前台时被调用  
    @Override  
    protected void onRestart() {  
    	TimerInstance.getInstance().stop();
        super.onRestart();  
    }
  
    //Activity创建或者从被覆盖、后台重新回到前台时被调用  
    @Override  
    protected void onResume() {  
        super.onResume();  
        isBack = false;
    } 
      
    //Activity被覆盖到下面或者锁屏时被调用  
    @Override  
    protected void onPause() {
        super.onPause();  
        //有可能在执行完onPause或onStop后,系统资源紧张将Activity杀死,所以有必要在此保存持久数据  
        TimerInstance.getInstance().stop();
    }

    /**
     * 登陆
     * @param v
     */
    public void loginClick(View v){
//    	if(true){
//    		view_password.setText("");
//    		Toast.makeText(LoginActivity.this, inputString.toString(), Toast.LENGTH_LONG).show();
//    		return;
//    	}
////    
    		
        String userName = view_userName.getText().toString();
        if (userName.equals("")){
            this.showMessage(getResources().getString(R.string.param235));
            return;
        }
		//view_password.setText("********");
        String passWork = view_password.getText().toString();
        if (passWork.equals("")){
            this.showMessage(getResources().getString(R.string.param236));
            return;
        }
//        if (NetUtil.isNetworkConnected(this)){
//        	mLoginPresenter.getTokenForLogin(userName);
//        } else {
//        	loginByLocal();
//        }
       boolean isAvailable=isNetworkConnected(this);
       if(isAvailable){
    	  String mm = "";
		try {
			mm = Encryption.encrypt(inputString.toString());
			//mm = Encryption.encrypt("Ab123456");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	   mLoginPresenter.getTokenForLogin(userName ,mm);
    	  
       }else{
    	   loginByLocal();
       }
       
        
    }
    public boolean isNetworkConnected(Context context) {  
    	      if (context != null) {  
    	          ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
    	                  .getSystemService(Context.CONNECTIVITY_SERVICE);  
    	         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();  
    	          if (mNetworkInfo != null) {  
    	              return mNetworkInfo.isAvailable();  
    	          }  
    	      }  
    	     return false;  
    	 }  
    
    @Override
    public void loginByLocal(){
    	this.showProgressDialog(getResources().getString(R.string.param237));
    	String userName = view_userName.getText().toString();
    	String passWork = view_password.getText().toString();
    	try {
			passWork = Encryption.encrypt(inputString.toString());
			//passWork = Encryption.encrypt("Ab123456");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.hideProgressDialog();
			this.showMessage(getResources().getString(R.string.param238));
			return;
		}
    	TAppYh user = new TAppYh();
    	user.setZh(userName);
    	user.setMm(passWork);
    	
    	mLoginPresenter.loginByLocal(user);
    }

    /**
     * 清空账号密码
     * @param v
     */
    public void resetClick(View v) {
        view_userName.setText("");
        view_password.setText("");
    }

    @Override
    public void loginSuccess(TAppYh user){
    	
        Map<String, Object> maps = new HashMap<String, Object>();
        
        if (view_rememberMe.isChecked()) {
        	maps.put(AppUtil.SHARE_LOGIN_USERNAME, view_userName.getText().toString());
        } else {
        	maps.put(AppUtil.SHARE_LOGIN_USERNAME, "");  // 2010-3月-31上午， 保存密码这边重置。
        }
        
//        maps.put(AppUtil.SHARE_LOGIN_USERNAME, view_userName.getText().toString());
        
        maps.put(AppUtil.SHARE_LOGIN_SFZ, user.getSfz());
        maps.put(AppUtil.SHARE_DATA_USER, GsonUtil.getGson().toJson(user));
    	
    	SharedPreferencesUtil.saveSharePreferences(this, AppUtil.SHARE_LOGIN_TAG, maps);
    	view_password.setText("");
    	Intent intent=new Intent();
        intent.setClass(LoginActivity.this, MainTabActivity.class);
        startActivity(intent);
    }

    @Override
    public void showProgressDialog(String msg) {
    	if(mDialogLoader != null){
			mDialogLoader.setMessage(msg);
			mDialogLoader.show();
		}
    }

    @Override
    public void hideProgressDialog() {
    	mDialogLoader.hide();
    }

    @Override
    public void showMessage(String msg) {
    	Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
       // BaseToast.getInstance().ShowSystemToast(LoginActivity.this, msg);
    }

    /** 弹出关于对话框 */
    private void alertAbout() {
        new AlertDialog.Builder(LoginActivity.this).setTitle(R.string.MENU_ABOUT)
                .setMessage(R.string.aboutInfo).setPositiveButton(
                R.string.ok_label,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                    }
                }).show();
    }
    
    private void exit(){
    	finish();
    }

	@Override
	public TAppYh getUser() {
		// TODO Auto-generated method stub
		TAppYh user = new TAppYh();
    	String userName = view_userName.getText().toString();
    	String passWork = view_password.getText().toString();
    	try {
			passWork = Encryption.encrypt(inputString.toString());
			//passWork = Encryption.encrypt("Ab123456");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	user.setZh(userName);
    	user.setMm(passWork);
    	user.setBmmc(BankApplication.mInstance.getDeviceByShare());
		return user;
	}

	@Override
	public void AlertDialog() {
		// TODO Auto-generated method stub
		new AlertDialog.Builder(this).setTitle("系统提示").setMessage(getResources().getString(R.string.param240)).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
//				Intent intent = new Intent();
//				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//				ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
//				intent.setComponent(comp);
//				startActivity(intent);
				// TODO 申请打开任务管理权限 
				try {
		            Intent intent = new Intent();
		            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
		            intent.setComponent(comp);
		            startActivity(intent);
		        } catch (Exception e) {
		            e.printStackTrace();
		            gotoMiuiPermission();
		        }
				
			}
		}).setNegativeButton("返回", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
		}).show();
	}
	
	/** 
	 * 跳转到miui的权限管理页面 
	 */  
	private void gotoMiuiPermission() {  
	    Intent i = new Intent("miui.intent.action.APP_PERM_EDITOR");  
	    ComponentName componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");  
	    i.setComponent(componentName);  
	    i.putExtra("extra_pkgname", getPackageName());  
	    try {  
	        startActivity(i);  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	        getAppDetailSettingIntent();
	    }  
	} 
	
	
	
	/** 
	 * 获取应用详情页面intent 
	 * 
	 * @return 
	 */  
	private Intent getAppDetailSettingIntent() {  
	    Intent localIntent = new Intent();  
	    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
	    if (Build.VERSION.SDK_INT >= 9) {  
	        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");  
	        localIntent.setData(Uri.fromParts("package", getPackageName(), null));  
	    } else if (Build.VERSION.SDK_INT <= 8) {  
	        localIntent.setAction(Intent.ACTION_VIEW);  
	        localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");  
	        localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());  
	    }  
	    return localIntent;  
	}
	boolean isBack = false;
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		isBack = true;
		return super.onKeyDown(keyCode, event);
	}


	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		new Thread(new Runnable() {
            @Override
            public void run() {
                // 白名单
                boolean safe = AntiHijackingUtil.checkActivity(getApplicationContext());
                // 系统桌面
                boolean isHome = AntiHijackingUtil.isHome(getApplicationContext());
                // 锁屏操作
                boolean isReflectScreen = AntiHijackingUtil.isReflectScreen(getApplicationContext());
                // 判断程序是否当前显示
                if (!safe && !isHome && !isReflectScreen && !isBack) {
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), R.string.activity_safe_warning,
                            Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        }).start();
		
	}  
	
	
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void Notification(CjkhjlListEvent cjkhjlListEvent) {		//
		switch (cjkhjlListEvent.getType()){
			case CjkhjlListEvent.DOWN_HOME_KEY:			
			
				break;
			
		}
	}

	@Override
	protected void onDestroy() {
		mDialogLoader.dismiss();
		super.onDestroy();
	}
}
